using Finance.Api.Write.Applications.Commands.调拨出库管理;
using Finance.Domain.调拨;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using Finance.Common;
using MediatR;
using AutoMapper;

namespace Finance.Api.Write.Applications.CommandHands.调拨出库管理
{
    public class DeployOutAddCommandHandler : IRequestHandler<DeployOutAddCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<DeployOut> db;
        private readonly SqlsugarDb<DeployOutDetail> dc;
        private readonly SqlsugarDb<ProductModel> productDb;
        private readonly SqlsugarDb<OutInModel> outInDb;
        private readonly IMapper mapper;

        public DeployOutAddCommandHandler(SqlsugarDb<DeployOut> db, IMapper mapper, SqlsugarDb<DeployOutDetail> dc, SqlsugarDb<ProductModel> productDb, SqlsugarDb<OutInModel> outInDb)
        {
            this.db = db;
            this.mapper = mapper;
            this.dc = dc;
            this.productDb = productDb;
            this.outInDb = outInDb;
        }

        public async Task<ApiResult<int>> Handle(DeployOutAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(request.OutNo))
                {
                    result.message = "出库单号不能为空";
                    result.Code = Enumcode.fail;
                    return result;
                }

                if (string.IsNullOrEmpty(request.OutType))
                {
                    result.message = "出库类型不能为空";
                    result.Code = Enumcode.fail;
                    return result;
                }

                if (string.IsNullOrEmpty(request.Deployment))
                {
                    result.message = "调拨单号不能为空";
                    result.Code = Enumcode.fail;
                    return result;
                }

                if (string.IsNullOrEmpty(request.OutBox))
                {
                    result.message = "调出仓库不能为空";
                    result.Code = Enumcode.fail;
                    return result;
                }

                if (request.DetailList == null || request.DetailList.Count == 0)
                {
                    result.message = "出库明细不能为空";
                    result.Code = Enumcode.fail;
                    return result;
                }

                // 映射主表数据
                var addResult = new DeployOut
                {
                    OutNo = request.OutNo,
                    OutType = request.OutType,
                    Deployment = request.Deployment,
                    OutBox = request.OutBox,
                    OutTime = request.OutTime,
                    Outmessage = request.Outmessage,
                    CreateTime = DateTime.Now,
                    CreateName = "管理员",
                    LoginId = 1,
                    IsDelete = false
                };

                var rows = await db.BeginTransaction(async () =>
                {
                    var mainId = await db.AddReturnId(addResult);
                    if (mainId == 0)
                    {
                        result.message = "添加失败";
                        result.data = 0;
                        result.Code = Enumcode.fail;
                        return 0;
                    }

                    // 插入明细表
                    var detailEntity = new List<DeployOutDetail>();

                    foreach (var detail in request.DetailList)
                    {
                        var outDetail = new DeployOutDetail
                        {
                            ProductNo = detail.ProductNo,
                            ProductName = detail.ProductName,
                            ProductNum = detail.ProductNum,
                            DeploymentNum = detail.DeploymentNum,
                            OutNumNow = detail.OutNumNow,
                            OutBoxLocation = detail.OutBoxLocation,
                            OutId = mainId,
                            CreateTime = DateTime.Now,
                            CreateName = "管理员",
                            LoginId = 1,
                            IsDelete = false
                        };

                        detailEntity.Add(outDetail);
                    }

                    var detailReturn = await dc.Addlist(detailEntity);
                    
                    // 更新产品状态
                    foreach (var detail in request.DetailList)
                    {
                        // 查找产品
                        var product = await productDb.FirstQuery().Where(p => p.ProductNo == detail.ProductNo && p.IsDelete == false).FirstAsync();
                        
                        if (product != null)
                        {
                            // 使用ProductStatusHelper更新产品信息
                            var updateResult = ProductStatusHelper.UpdateProductInfo(product, detail.OutNumNow, false);
                            
                            if (!updateResult.IsSuccess)
                            {
                                throw new Exception($"产品 {detail.ProductName} 更新失败: {updateResult.Message}");
                            }
                            
                            await productDb.Updata(updateResult.UpdatedProduct);

                            // 添加出入库记录
                            var outInRecord = new OutInModel
                            {
                                OutInNo = request.OutNo,
                                OutInTime = request.OutTime,
                                OutInType = 1, // 1表示出库
                                LocationName = request.OutBox ?? product.Location,
                                GoinNumber = 0, // 入库数量为0
                                OutNumber = detail.OutNumNow, // 出库数量
                                ProductNo = detail.ProductNo,
                                ProductName = detail.ProductName,
                                CreateTime = DateTime.Now,
                                CreateName = "管理员",
                                LoginId = 1,
                                IsDelete = false
                            };
                            await outInDb.AddAsync(outInRecord);
                        }
                    }
                    
                    return detailReturn;
                });

                if (rows > 0)
                {
                    result.message = "调拨出库添加成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "调拨出库添加失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }
            }
            catch (Exception ex)
            {
                result.message = "调拨出库添加失败: " + ex.Message;
                result.Code = Enumcode.fail;
            }

            return result;
        }
    }
} 